package zhoufu.sz.sanxiao_check.ui.check;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import zhoufu.sz.sanxiao_check.R;
import zhoufu.sz.sanxiao_check.models.CheckBook;
import zhoufu.sz.sanxiao_check.models.CheckItemModel;
import zhoufu.sz.sanxiao_check.utils.FileUtils;


/**
 * 项目 : DaLang_GongKuang_Law
 * 作者 : HYC
 * 时间 : 2016/1/15 18:07
 * 功能 : html页面预览
 */
public class PreHtmlViewActivity extends AppCompatActivity
{
    public final static String mPrintPackageName = "com.dynamixsoftware.printershare";// 佳能打印

    private WebView   _webView;
    private File      outputFile;
    private CheckBook book;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prehtml);
        _webView = (WebView) findViewById(R.id.webView);
        _webView.setWebViewClient(new WebViewClient());
        _webView.setWebChromeClient(new WebChromeClient());
        WebSettings webSettings = _webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBlockNetworkImage(false);
        _webView.addJavascriptInterface(this, "android");
        //设置可以支持缩放
        webSettings.setSupportZoom(true);
        // 设置出现缩放工具
        webSettings.setBuiltInZoomControls(true);
        //设置可在大视野范围内上下左右拖动，并且可以任意比例缩放
        webSettings.setUseWideViewPort(true);
        webSettings.setDomStorageEnabled(true);
        //设置默认加载的可视范围是大视野范围
        webSettings.setLoadWithOverviewMode(true);
        //自适应屏幕
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        Intent intent = getIntent();
        book = intent.getParcelableExtra("CheckBook");
        if ( savedInstanceState != null )
        {
            book = savedInstanceState.getParcelable("book");
        }
        initData();
    }

    private void initData()
    {

        File badgeFile = new File(getExternalCacheDir(), "badge.png");
        book.setPath("file://" + badgeFile.getPath());
        savebadge(badgeFile);
        outputFile = new File(getExternalCacheDir(), "LC_work_check.html");
        _webView.loadUrl("file:///android_asset/check_book.html");
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        callJsMethod(gson, book);
    }

    private void callJsMethod(final Gson gson, final CheckBook book)
    {
        _webView.postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                String json = gson.toJson(book);

                Log.e("callJsMethod", json);
                _webView.loadUrl("javascript:setData('" + json + "')");
            }
        }, 800);
    }

    @JavascriptInterface
    public void setResult(String html)
    {
        try
        {
            save(html);
            print();
        } catch (Exception e)
        {

        }
    }

    private void save(String html) throws IOException
    {
        FileOutputStream fos = new FileOutputStream(outputFile);
        fos.write(html.getBytes());
        fos.close();
    }

    void print()
    {
        Intent i = new Intent("android.intent.action.VIEW");
        i.addCategory(Intent.CATEGORY_DEFAULT);
        i.setPackage(mPrintPackageName);
        i.setDataAndType(Uri.fromFile(outputFile), "text/html");
        startActivity(i);
    }

    public void onPrint(View v)
    {
        _webView.postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                _webView.loadUrl("javascript:print()");
            }
        }, 20);
    }

    public static void startAct(Context context, CheckItemModel item)
    {
        Intent intent = new Intent(context, PreHtmlViewActivity.class);
        intent.putExtra("CheckBook", new CheckBook(item));
        context.startActivity(intent);
    }

    private void savebadge(File badgeFile)
    {
        if ( badgeFile.exists() )
        {
            badgeFile.delete();
        }
        InputStream      inputStream;
        FileOutputStream outputStream;
        try
        {
            inputStream = getAssets().open("badge.png");
            outputStream = new FileOutputStream(badgeFile);
            FileUtils.copy(inputStream, outputStream);
            if ( inputStream != null )
            {
                inputStream.close();
            }
            if ( outputStream != null )
            {
                outputStream.close();
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    @Override protected void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        outState.putParcelable("book", book);
    }
}
